<?php

namespace App\Http\Controllers;

use App\Assorts;
use App\Boxs;
use App\Goods;
use App\Tags;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;

class BoxController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $boxs = Boxs::orderBy('updated_at', 'desc')->paginate(15);
        $tags = Tags::all();

        return view('system.box.index',compact(['boxs','tags']));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $boxs = Boxs::where('mobile',$id)->orWhere('name', $id)->orWhere('express_out_no',$id)->paginate(15);
        $tags = Tags::all();

        return view('system.box.index',compact(['boxs','tags']));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $box = Boxs::where('orderno',$id)->get();

        return view('system.box.edit',compact('box'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $iserror=false;
        
        $assorts = Assorts::where('orderno',$id)->get();

        foreach ($assorts as $assort) {

            $good = Goods::where('id',$assort->goods_id)->first();
            
            if($good!=null){
                $good->number = $good->number +1;
                $good->save();
                $assort->delete();
            }else{
                $iserror =true;
            }
        }

        $box = Boxs::where('orderno',$id);
        if(!$iserror) {
            $box->delete();
        }
    }

    public function ajaxremark(Request $request)
    {
        $this->validate($request, [
            'remark' => 'required',
            'orderno'=> 'required',
        ]);

        Boxs::where('orderno',$request->get('orderno'))->update(["remark"=>$request->get('remark')]);
    }
}
